import { _decorator, Component, Node, Prefab, MeshRenderer, v3, instantiate } from 'cc';
import { LoadItemPrefabByName, OpenItems } from '../../../../configs/Levels';
import BasePanel from '../../../core/component/BasePanel';
import Data from '../../../core/manager/Data';
import WXTTUtils from '../../../core/manager/WXTTUtils';
import AudioMgr from '../../../core/utils/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('NewPackOpenedLayer')
export class NewPackOpenedLayer extends BasePanel {
    onBtnClicked(event: any, customEventData: any) {
        AudioMgr.Instance().playSFX('btnclick')
        this.close();
    }
    show() {
        
        WXTTUtils.showInterstitialAd();
        let node_items = this.GetGameObject("node_items");
        node_items.children.map(a => a.active = false);

        let ids = [];
        for (var i = Data.user.openIndex; i < Data.user.openIndex + 8 && i < OpenItems.length; ++i) {
            ids.push(OpenItems[i]);
        }
        for (var i = 0; i < node_items.children.length; ++i) {
            let child = node_items.children[i];
            child.active = true;
            this.setMesh(child, ids[i]);
        }

        Data.user.openIndex += 8;
        Data.user.openIndex = Math.min(Data.user.openIndex, OpenItems.length - 1);
        Data.save();
    }

    private setMesh(node: Node, name: string) {
        LoadItemPrefabByName(name).then((res: any) => {
            let tmp: Node = instantiate(res);
            let render = tmp.getComponentInChildren(MeshRenderer) as MeshRenderer;
            let mesh = render.mesh;
            node.scale = render.node.scale.multiplyScalar(100);
            node.getComponent(MeshRenderer).mesh = mesh;
            tmp.destroy();
        })
    }
}

